new Vue({
  el: "#app",
  data: {
    ossImgUrl: ossImgUrl,//oss图片域名
    env: '',//判断环境
    screenHeight: document.documentElement.clientHeight,     // 当前高度
    originHeight: document.documentElement.clientHeight,     //默认高度，用作比较
    isOriginHeight: true,    //当前高度是否仍等于默认高度
    enp_user: "",//姓名
    typeData: [//证件类型可选项
      { value: 0, text: '大陆' },
      { value: 1, text: '香港' },
      { value: 2, text: '澳门' },
      { value: 3, text: '台湾' },
      { value: 4, text: '外籍' }
    ],
    user_type: '',//证件类型 0 大陆 1 香港 2 澳门 3 台湾 4
    user_name: "",//证件类型中文(接口不传)
    user_number: "",//证件号
    user_front_img: '',//证件照正面
    user_verso_img: '',//证件照反面
    bank_name: '',//开户行
    bank_num: '',//开户账号
    province_id: '',//省ID
    city_id: '',//市ID
    address: '',//常住地址
    email: "",//邮箱
    flag: false,//下一步是否可点击
  },
  watch: {
    screenHeight(val) {
      if (this.originHeight - val > 60) {    //这里以防万一改了下判断形式，当屏幕高度减少了60px以上时才隐藏footer
        this.isOriginHeight = false;
      } else {
        this.isOriginHeight = true;
      }
    }
  },
  created() {
    this.getAddressData();
    // 缓存地址栏 phone 参数
    if (getUrlParam("phone")) {
      local.set("phone", getUrlParam("phone"));
    }
  },
  mounted() {
    // 判断是否在小程序内
    var u = window.navigator.userAgent;
    var that = this;
    if (/MicroMessenger/i.test(u)) {//判断是否是微信环境
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {// 小程序
          that.env = 'mp';
        }
      })
    }
    // 解决底部被键盘顶起的问题
    window.onresize = () => {
      return (() => {
        this.screenHeight = document.documentElement.clientHeight;
      })()
    }
    this.queryInfo();
  },
  methods: {
    // 个人签基本信息查询
    queryInfo: function () {
      var that = this;
      get("api/single/user/show").then(function (res) {
        if (res.data) {
          that.fillData(res.data);
        }
      })
    },
    // 填入查询的数据
    fillData: function (data) {
      var that = this;
      this.enp_user = data.enp_user;
      this.user_type = data.user_type;
      this.typeData.map(function (item) {
        if (item.value == that.user_type) {
          that.user_name = item.text;
        }
      })
      this.user_number = data.user_number;
      this.user_front_img = data.user_front_img ? httpImgUrl + data.user_front_img : "";
      this.user_verso_img = data.user_verso_img ? httpImgUrl + data.user_verso_img : "";
      this.bank_name = data.bank_name;
      this.bank_num = data.bank_num;
      this.province_id = data.province_id;
      this.city_id = data.city_id;
      this.getAddressData().then(function (res) {
        var cityName = [];
        res.map(function (item) {
          if (item.id == that.province_id) {
            cityName.push(item.text)
          }
          if (item.children) {
            item.children.map(function (el) {
              if (el.id == that.city_id) {
                cityName.push(el.text)
              }
            })
          }
        });
        that.address = cityName.join("");
      })
      this.email = data.email;
      this.mustClick();//检测下一步按钮是否高亮
    },
    // 失去焦点验证下一步是否可点击
    mustClick: function () {
      if (!this.enp_user) {
        this.flag = false
      } else if (!this.user_type && this.user_type != 0) {
        this.flag = false
      } else if (!this.user_number) {
        this.flag = false
      } else if (this.user_type != 0 && (!this.user_front_img || !this.user_verso_img)) {
        this.flag = false
      } else if (!this.bank_name) {
        this.flag = false
      } else if (!this.bank_num) {
        this.flag = false
      } else if (!this.province_id && !this.city_id) {
        this.flag = false
      } else {
        this.flag = true
      }
    },
    // 选择证件类型 0大陆(身份证) 1香港 2澳门 3台湾 4外籍
    selectType: function () {
      document.activeElement.blur(); //收起键盘
      var that = this
      var selectorFr = new mui.PopPicker();
      selectorFr.setData(that.typeData)
      selectorFr.show(function (item) {
        that.user_type = item[0].value
        that.user_name = item[0].text
        that.mustClick();
      })
    },
    //证件号验证位数验证（8位到18位）
    verifyId: function () {
      if (!this.user_number) { return }
      if (this.user_number.length < 8) {
        mui.toast('证件号必须在8位到18位之间');
        this.user_number = "";
      }
      this.mustClick();
    },
    // 上传照片通用方法
    upLoad: async function (inputName, type) {
      var inputDOM = this.$refs[inputName];
      var file = inputDOM.files[0]
      //判断是否是图片类型
      if (!/image\/\w+/.test(file.type)) {
        mui.toast("只能选择图片");
        return false;
      }
      var base64 = await this.repairPhoto(file, 0.9, 720);
      switch (type) {
        case 4://证件照正面
          this.user_front_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_front_img = httpImgUrl + url;
          break;
        case 5://证件照反面
          this.user_verso_img = base64 //预览页面上预留一个img元素，载入base64
          var url = await this.uploadHttp(base64)
          this.user_verso_img = httpImgUrl + url;
          break;
      }
      this.mustClick();
    },
    // 整体调用
    repairPhoto: async function (file, num, w) {
      const result = await this.isNeedFixPhoto(file);
      const resultBase64 = await this.file2Base64(file);
      const Orientation = result.Orientation;
      const numb = num || 1;
      if (result.flag) {// 处理旋转
        return await this.best4Photo(resultBase64, Orientation, numb, w)
      } else { // 不处理旋转
        return await this.best4Photo(resultBase64, 1, numb, w)
      }
    },
    // 压缩处理选中的方法
    best4Photo: function (resultBase64, Orientation, num, w) {
      return new Promise(function (resolve, reject) {
        var image = new Image();
        image.src = resultBase64;
        image.onload = function () {
          var imgWidth = w;
          var imgHeight = w * this.height / this.width; //获取图片宽高
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext('2d');
          canvas.width = imgWidth;
          canvas.height = imgHeight;
          if (Orientation && Orientation != 1) {
            switch (Orientation) {
              case 6:     // 旋转90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(Math.PI / 2);
                ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                break;
              case 3:// 旋转180度
                ctx.rotate(Math.PI);
                ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                break;
              case 8:     // 旋转-90度
                canvas.width = imgHeight;
                canvas.height = imgWidth;
                ctx.rotate(3 * Math.PI / 2);
                ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                break;
            }
          } else {
            ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
          }
          const result = canvas.toDataURL("image/jpeg", num);
          resolve(result)
        }
      })
    },
    // 上传图片到服务器
    uploadHttp: function (base64) {
      var filename = new Date().getTime() + "_" + (Math.random() * 100000).toFixed(0);
      return new Promise(function (resolve, reject) {
        post("api/upload/base64", {
          file: base64,
          filename: filename,
          dirPath: 'credentials'
        }).then(function (res) {
          var url = res.data.url;
          resolve(url)
        })
      })
    },
    // 判断图片是否需要旋转
    isNeedFixPhoto: function (file) {
      return new Promise(function (resolve, reject) {
        EXIF.getData(file, function () {
          var Orientation = EXIF.getTag(this, 'Orientation');
          if (Orientation && Orientation != 1) {
            //图片角度不正确
            resolve({ flag: true, Orientation: Orientation })
          } else {
            //不需处理直接上传
            resolve({ flag: false, Orientation: Orientation })
          }
        })
      })
    },
    // 将file文件 读成base64码 
    file2Base64: function (file) {
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
          resolve(ev.target.result);
        }
      })
    },
    // 删除照片通用方法
    deletePic: function (type) {
      switch (type) {
        case 4://证件照正面
          this.user_front_img = "";
          break;
        case 5://证件照反面
          this.user_verso_img = "";
          break;
      }
      this.mustClick();
    },
    // 验证银行卡号 位数验证（16位到20位），由于里面有空格，所以最小为19最大位24
    verifyBank_num: function () {
      if (!this.bank_num) { return }
      if (this.bank_num.replace(/\s*/g, "").length < 16) {
        mui.toast('开户账号必须在16位到20位之间');
        this.bank_num = "";
      }
      this.mustClick();
    },
    // 接口获取地址可选项
    getAddressData: function () {
      var that = this;
      return new Promise(function (resolve, reject) {
        post("api/address/index").then(function (res) {
          var data = [...res.data];
          var cityData = [];
          data.map(function (item) {
            var child = [];
            item.children.map(function (el) {
              child.push({
                id: el.id,
                text: el.name,
                pid: el.pid,
                children: el.children
              })
            })
            cityData.push({
              id: item.id,
              text: item.name,
              pid: item.pid,
              children: child
            })
          });
          that.cityData = cityData;
          resolve(cityData);
        })
      })
    },
    // 选择常住地址
    selectAddress: function () {
      document.activeElement.blur(); //收起键盘
      var that = this
      var selector = new mui.PopPicker({
        layer: 2   //显示列数
      })
      selector.setData(that.cityData)
      selector.show(function (item) {
        that.province_id = item[0].id;//省ID
        that.city_id = item[1].id//市ID
        that.address = item[0].text + " " + item[1].text;//常住地址
        that.mustClick();
      })
    },
    //email验证
    emailReg: function () {
      if (!this.email) { return }
      var ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if (!ePattern.test(this.email)) {
        mui.toast('请输入正确的邮箱');
        this.email = "";
        this.mustClick();
      }
    },
    // 下一步
    submit: function () {
      var that = this;
      if (!this.flag) {
        return
      }
      post("api/single/user", {
        enp_user: this.enp_user,
        user_type: this.user_type,
        user_number: removeBlank(this.user_number),
        bank_name: this.bank_name,
        bank_num: removeBlank(this.bank_num),
        province_id: this.province_id,
        city_id: this.city_id,
        user_front_img: this.user_front_img ? this.user_front_img.split('/').slice(3).join('/') : null,////去除域名 
        user_verso_img: this.user_verso_img ? this.user_verso_img.split('/').slice(3).join('/') : null,
        email: this.email ? this.email : null,
      }).then(function (res) {
        if (res.data) {
          if (res.data.auth_status == 3) {//认证成功->跳协议页
            window.location.href = "sign.html";
          } else {//->跳填写验证码页
            window.location.href = "short_code.html?flow_id=" + res.data.flow_id + "&user_number=" + removeBlank(that.user_number) + "&user_phone=" + local.get("phone");
          }
        }
      })
    }
  }
})